import React from 'react';
import { connect } from 'dva';
import './index.less';
import Modal from '../../components/Sideslip/Sideslip';
import { Message,message, Select, Button,  Form, Input, Radio, InputNumber,Row,Col,Card,Checkbox, Icon,Cascader} from 'antd';
import {reg_REG1, VER_PHONE, ID_CORD, ZHUZHI_REG} from '../../common/system';
import {serviceTypeAll, InsertOldList, getGender, getServicePeople, selectDeptTree,upOldInfo} from '../../services/api';
import { formatCascader } from '../../common/common';
import History from './historyForm';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;


class AddModal extends React.Component{
    constructor(props){
       super(props);
    }

    componentDidMount(){
        this.props.dispatch({type: 'example/setAreaInfo',res:this.props.areaInfo});  //区域
    }
    closeModal = () => {
        this.props.operateModal();
    }
    
    updatas = () => {
        this.props.upData_();
    }
    
    render() {
        const {show} = this.props;
        return (
            <Modal visable={this.props.visable} closeModal={this.closeModal} >
            {
                show === 'history' ? <History queryHistory={this.props.queryHistory} id={this.props.selsectOldId} historyList={this.props.historyList}/> :  
                <div className="warp_">
                {show === 'add' ?  <p>新增客户</p> :
                 (show === 'upData' ) ? <p>修改客户</p> : <p>详情</p>
                 }
                  <CreateCompany
                    ref={(ref)=>this.createCompany = ref}
                    // visible={this.state.visible}
                    onCancel={this.handleCancel}
                    onCreate={this.handleCreate}
                    // loading={this.state.createLoading}
                    closeModal={this.closeModal}
                    upDatas={this.updatas}
                    show={show}
                    valueArr={this.props.valueArr}
                    getInfo={this.props.getInfo}
                    areaInfo={this.props.areaInfo}
                />
                </div>
            }
            </Modal>
            
        );
    }
}
export default connect((state)=>({
	areaInfo: state.example.areaInfo,
}))(AddModal);

class CreateFormComponent extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            content:[],   //服务内容
            list: this.props.show === 'add' ? [        //家属信息组
                {
                   fid:1,
                   fName:'',
                   fPhone:'',
                   fGender:'',
                   fRelation:'',
                   fAddress:''
                }
            ] : this.props.valueArr.list,   

            num:2,
            value: '', 
            gender:[],  //性别
            servicePeople:[],   //服务负责人信息
            area:[],   //区域
            // areas:'',

            obj:this.props.valueArr,     //addModal获取到的详情数据
            click:false,  //disabled
            require:true,  //是否为必填项

            contentId:'',

            areaArr:[],   // 区域数组
        }
    }


    componentDidMount(){
        this.getGender();        //性别
        this.serviceTypeAll();   //服务内容
        this.getServicePeople();      //服务负责人
        this.check();       //disabled
    }

    // this.props.valueArr  是主页面查询详情请求到的数据

    check(){
        if(this.props.show === 'detail'){
            this.setState({
                click:true,
            })
        }
    }

     //获取服务内容
    async serviceTypeAll(){
        const response = await serviceTypeAll({pageCurrent:0,pageSize:0});
        if(response.code === 200){
           this.setState({
               content:response.data.dataList
           })
        } else {
            response.msg && message.error(response.msg);
        }
    }

    //获取服务负责人信息
    async getServicePeople(){
           const response = await getServicePeople({pageCurrent:0,pageSize:0});
           if(response.code === 200){
              this.setState({
                  servicePeople:response.data.dataList
                })   
           } else {
               response.msg && message.error(response.msg);
           }
       } 

    //获取区域信息
     async getSelectDeptTree(){
           const response = await selectDeptTree();
           if(response.code === 200){
            this.setState({
                area:response.data
            })
           } else {
            response.msg && message.error(response.msg);
           }
    }

     //获取性别 
    async getGender(){
           const response = await getGender();
           if(response.code === 200){
             this.setState({
                 gender:response.data
             })
           } else {
               response.msg && message.error(response.msg);
           }
    }
       

      //新增
	async InsertOldList(data){
        if(!data){
          message.error('请填写相关信息');
          return
        }
		const response = await InsertOldList(data);
        if(response.code === 200){
            this.props.getInfo({pageCurrent:0,pageSize:0});
            this.cancel_();
            Message.success('新增成功')
        } else {
            response.msg && message.error(response.msg);
        }
    }
    //提交表单时，调用新增接口
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if(!err){
                console.log('values.fStreetCommunity',values.fStreetCommunity)
                if(values.fStreetCommunity.length < 3){
                    message.error('请选择老人所在社区');
                    return
                }
                values.fStreetCommunity = values.fStreetCommunity.join(",");
                let arr = [...this.state.list];
                let obj = {
                    ...values,
                    list:arr.map(item => {
                       delete item.fid;
                       return item
                    }),
                    fContentId:this.state.contentId
                };
                this.InsertOldList(obj);
            } 
        });
      }

    //修改
    async upOldInfo(obj){
		const response = await upOldInfo(obj);
        if(response.code === 200){
            this.cancel_();  //关闭modal
            this.props.getInfo({pageCurrent:0,pageSize:0});
            Message.success('修改成功')
        } else {
            response.msg && message.error(response.msg);
        }
    }
    //提交表单时，调用修改接口
    handleSubmits = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if(!err){
                values.fStreetCommunity = values.fStreetCommunity.join(",");
                let obj_ = {
                    ...values,
                    list:this.refs.FamilyList.state.arr,
                    fContentId:values.fContentId.join(","),
                    fId:this.state.obj.fId
                };
                this.upOldInfo(obj_);
            }   
        });   
      }

     
   

    //给家属数据组重新
    setValue = (value, index, attrName) => {
        let arr = [...this.state.list];
        arr[index][attrName] = value;
        this.setState({
            list: arr
        })
    }


    //取消按钮
    cancel_ = () => {
        this.props.closeModal();
    }
    
    //服务内容
    change1 = (value) =>{
        this.setState({
            contentId:value.join(',')
        })
    }
    
    onChange = (e) => {
        this.setState({
          value: JSON.stringify(e.target.value),
        });
      }
  

    render() {
      //性别
      const Gender = this.state.gender.map((item)=>Object.assign({},{label:`${item.fContent}`,value:`${item.fId}`}));
      const formItemLayout = {
        labelCol: { span: 9 },
        wrapperCol: { span: 15},
      };
      const formItemLayouts = {
        labelCol: { span: 4 },
        wrapperCol: { span: 20},
      };
      const formItemLayout_ = {
        labelCol: { span: 3 },
        wrapperCol: { span: 21},
      };
      const formItemsLayout = {
        labelCol: { span: 18 },
        wrapperCol: { span: 6},
      };
      const { visible, onCancel, onCreate, form, loading } = this.props;
      const { getFieldDecorator } = form;

      const {click,obj} = this.state;

      return (    
          <Form layout="inline" style={{width: '100%'}} >
            <Row   type="flex" justify="space-around">
				<Col span={12} >
                    <FormItem label="老人姓名" {...formItemLayout} whitespace>
                    {getFieldDecorator('fName', {
                        rules: [{ required:true, message: '姓名不能为空' },{pattern: reg_REG1, message: '输入格式不正确'}],
                        initialValue: obj.fName ? obj.fName : ''
                    })(
                        <Input  placeholder={this.state.click !== false ? '' : "请输入..." } disabled={click}/>
                    )}
                    </FormItem>
                </Col>
                <Col span={12} >
                    <FormItem label="老人电话" {...formItemLayout}>
                    {getFieldDecorator('fPhone', {
                        rules: [{ required: true, message: '电话不能为空' },{pattern: VER_PHONE, message: '电话号码格式不正确'}],
                        initialValue: obj.fPhone ? obj.fPhone:'' 
                    })(<Input  placeholder={this.state.click !== false ? '' : "请输入..." } disabled={click}/>)}
                    </FormItem>
                </Col>
            </Row>
            <Row   type="flex" justify="space-around">
				<Col span={12} >
                    <FormItem label="老人性别" {...formItemLayout} style={{marginLeft:14}}>
                    {getFieldDecorator('fGender', {
                        rules: [{ required:true , message: '请选择性别' }],
                        initialValue: obj.fGender ? obj.fGender :''
                    })(
                        <RadioGroup onChange={this.onChange}  options={Gender} style={{marginLeft:5}} setFieldsValue={this.state.value} disabled={click}></RadioGroup>
                    )}
                    </FormItem>
                </Col>
                <Col span={12} >
                    <FormItem label="老人年龄" {...formItemLayout} >
                    {getFieldDecorator('fAge', {
                        rules: [{ required: true, message: '年龄不能为空' }],
                        initialValue: obj.fAge ? obj.fAge : ''
                    })(<InputNumber min={1} placeholder={this.state.click !== false ? '' : "请选择..." } style={{width:'100%'}} disabled={click}/>)}
                    </FormItem> 
                </Col>
            </Row>
            <Row   type="flex" justify="space-around">
				<Col span={24} >
                    <FormItem label="老人住址" whitespace style={{width:'100%',marginLeft:14}}>
                    {getFieldDecorator('fAddress', {
                        rules: [{ required: true, message: '住址不能为空' },{pattern: ZHUZHI_REG, message: '请输入合法的内容'}],
                        initialValue: obj.fAddress ? obj.fAddress :''
                    })(<Input style={{width:'424px'}} placeholder={this.state.click !== false ? '' : "请输入..." } disabled={click}/>)}
                    </FormItem>
                </Col>
            </Row>
            <Row   type="flex" justify="space-around">
				<Col span={24} >
                    <FormItem label="身份证号" whitespace style={{width:'100%',marginLeft:26}}>
                    {getFieldDecorator('fCardId', {
                        rules: [
                            // { required:true, message: '身份证号码不能为空' },
                        {pattern: ID_CORD, message: '身份证号码格式不正确'}
                    ],
                        initialValue: obj.fCardId ? obj.fCardId :''
                    })(<Input style={{width:'424px'}} placeholder={this.state.click !== false ? '' : "请输入..." } disabled={click}/>)}
                    </FormItem>
                </Col>
            </Row>
            <Row   type="flex" justify="space-around">
                <Col span={24} >
                    <FormItem label="服务内容"  whitespace style={{width:'100%',marginLeft:26}}>
                    {getFieldDecorator('fContentId', {
                        // rules: [{ required: true, message: '请选择' }],
                        initialValue: obj.fContentId ? obj.fContentId.split(',') : []
                    })(
                        <Select  style={{ width: '424px',zIndex:9}}   onChange={this.change1}  placeholder={this.state.click !== false ? '' : "请选择..." } disabled={click} mode="multiple">
                        {
                            this.state.content.map((item)=>{
                               return(
                                <Option key={item.fId} value={item.fId}>{item.fName}</Option>
                               )
                            })
                        }
                        </Select>
                    )}
                    </FormItem>
                </Col>
             </Row>
             <Row   type="flex" justify="space-around">
				<Col span={24} >
                    <FormItem label="街办社区" {...formItemLayouts} whitespace  style={{width:'100%',marginLeft:6}}>
                    {getFieldDecorator('fStreetCommunity', {
                        rules: [{ required:true, message: '该项不能为空' }],
                        initialValue: obj.fStreetCommunityId ? obj.fStreetCommunityId.split(",") : []
                    })(
                        <Cascader disabled={click} options={this.props.areaInfo} placeholder={this.state.click !== false ? '' : "请选择..." }  changeOnSelect={true} style={{width:'95%'}}  allowClear/>
                    )}
                    </FormItem>
                </Col>
            </Row>
            <Row   type="flex" justify="space-around">
				<Col span={12} >
                    <FormItem label="服务负责人" {...formItemsLayout} whitespace style={{marginLeft:19,width:'45%'}}>
                    {getFieldDecorator('fServiceStaffId', {
                        // rules: [{ required: true, message: '请选择' }],
                        initialValue: `${obj.fServiceStaffId ? obj.fServiceStaffId :''}`
                    })(
                        <Select  style={{ width: '500%',zIndex:9}}   onChange={this.change} placeholder={this.state.click !== false ? '' : "请选择..." }  disabled={click}>
                        {
                            this.state.servicePeople.map((item)=>{
                               return(
                                <Option key={item.fId} value={item.fId}>{item.fName}({item.fPhone})</Option>
                               )
                            })
                        }
                        </Select>
                    )}
                    </FormItem>
                </Col>
                <Col span={12} >
                    <FormItem label="服务剩余次数" {...formItemLayout} >
                        {getFieldDecorator('fSurplusTimes', {
                            // rules: [{ required: true, message: '该项不能为空' }],
                            initialValue: obj.fSurplusTimes ? obj.fSurplusTimes: ''
                        })(
                            <InputNumber min={1} placeholder={obj.fSurplusTimes ? obj.fSurplusTimes : obj.fSurplusTimes === 0 ? obj.fSurplusTimes : "请选择..."} style={{ width: '100%'}} disabled={click}/>
                        )}
                    </FormItem>
                </Col>
            </Row>
            {/* 点击修改，查看，循环的数组是传回来的对象里面包含的list */}
            <FamilyList setValue={this.setValue}  Gender={Gender}  list={this.state.list} show={this.props.show} click={click} ref="FamilyList"/>
             
            <Row   type="flex" justify="space-around">
				<Col span={24} >
                    <FormItem label="备注" {...formItemLayout_} whitespace > 
                    {getFieldDecorator('fRemarks',{
                        initialValue: `${obj.fRemarks ? obj.fRemarks : ''}`,
                    })(
                        <TextArea style={{width:'500px'}} disabled={click} maxLength="50"  placeholder={this.state.click !== false ? '' : "(最多可输入50个汉字)" } />
                    )}
                    </FormItem>
                </Col>
            </Row>
            <Row   type="flex" justify="space-around">
				<Col span={24} >
                    <FormItem style={{textAlign: 'right',position:'absolute',marginTop:15,right:0}}>
                    
                    {this.props.show === 'add' ? 
                        <div >
                            <Button className="del" style={{marginRight:10}} onClick={this.cancel_}>取消</Button>
                            <Button className="ok" type="primary"  htmlType="submit" style={{backgroundColor:'#63A4F4',color:'white'}} onClick={this.handleSubmit}>确定</Button> 
                        </div>
                        :
                    (this.props.show === 'upData') ?
                        <div>
                            <Button className="del" style={{marginRight:10}} onClick={this.cancel_}>取消</Button>
                            <Button className="ok" type="primary"  htmlType="submit" style={{backgroundColor:'#63A4F4',color:'white'}} onClick={this.handleSubmits}>保存</Button> 
                        </div>
                    : null
                    }
                    
                    </FormItem>
            </Col>
            </Row>
          </Form>
      );
    }
  }
  
const CreateCompany = Form.create()(CreateFormComponent);

  
class FamilyList extends React.Component{
   state = {
       arr:this.props.list,
       name:'',
       phone:'',
       relation:'',
       address:'',
   }

      //点击增加模块
      add(){
        this.props.list.push({
          fid: this.props.list.length + 1,
          fName:'',
          fPhone: '',
          fGender: '',
          fRelation: '',
          fAddress: ''
        });
        this.setState({
            arr:this.props.list
        })
    }

    del(index){
        for(let i=0;i<this.props.list.length;i++){
           if(index === i){
            this.props.list.splice(i,1);
           }
        }
        this.setState({
            arr:this.props.list
        })
    }

    changeName(e,id) {
        for (let obj of this.state.arr) {
          if (id === obj.fid) {
            obj.fName = e.target.value;
            break;
          }
        }
        
      }
      
    changePhone(e,id) {
        for (let obj of this.state.arr) {
            if (id === obj.fid) {
              obj.fPhone = e.target.value;
              break;
            }
          }
      }

    changeRelation(e,id) {
        for (let obj of this.state.arr) {
            if (id === obj.fid) {
              obj.fRelation = e.target.value;
              break;
            }
          }    
    }
    changeAddress(e,id) {
        for (let obj of this.state.arr) {
            if (id === obj.fid) {
              obj.fAddress = e.target.value;
              break;
            }
          }    
    }
    
    render(){
      return(
          <div >
              {
                this.state.arr.length != 0 ?
                  this.state.arr.map((data,index) => {
                      return(
                        <Card style={{marginBottom:8,marginTop:8,marginLeft:20,width:'94%'}} key={index}>
                        {
                          index >0  ?  <Icon type="close" onClick={()=>this.del(index)} style={{cursor:'pointer'}}/> : null  
                        }
                       
                            <Row   type="flex" justify="space-around" style={{marginBottom:8}}>
                                <Col span={12} >
                                    <span style={{width:50,marginRight:5}}>家属姓名:</span>
                                    <Input style={{width:160}} defaultValue={data.fName} onChange={(e)=>this.changeName(e,data.fid)}  disabled={this.props.click} />
                                </Col>
                                <Col span={12} >
                                    <span style={{width:50,marginRight:5}}>家属电话:</span>
                                    <Input style={{width:160}} defaultValue={data.fPhone} onChange={(e)=>this.changePhone(e,data.fid)} disabled={this.props.click}/>
                                </Col>
                            </Row>
                            <Row   type="flex" justify="space-around" style={{marginBottom:8}}>
                                <Col span={12} >
                                    <span style={{width:50,marginRight:5}}>家属性别:</span>
                                    <RadioGroup style={{width:160}} onChange={(e)=>this.props.setValue(e.target.value, index,'fGender')}  options={this.props.Gender} defaultValue={data.fGender} disabled={this.props.click} ></RadioGroup>  
                                </Col>
                                <Col span={12} >
                                        <span style={{width:50,marginRight:5}}>关系类型:</span>
                                        <Input style={{width:160}} defaultValue={data.fRelation} disabled={this.props.click}   onChange={(e)=>this.changeRelation(e,data.fid)}/>
                                    
                                </Col>
                            </Row>
                            <Row   type="flex" justify="space-around" >
                                <Col span={24} >                               
                                    <span>家属住址:</span>
                                    <Input style={{width:385,marginLeft:5}} defaultValue={data.fAddress} disabled={this.props.click}  onChange={(e)=>this.changeAddress(e,data.fid)}/>                                
                                </Col>
                            </Row>
                       </Card> 
                      )
                  })
                  :null
              }  
              {
                  this.props.show === 'detail' ?  null:
                  <Button style={{width:'93%',marginBottom:8,marginLeft:25}} onClick={()=>this.add()}> +增加家属信息模块 </Button>
                  
              }    
            
          </div>
        
      )
    }
}



